# encoding: UTF-8
import time
import os
from pyalgotrade import observer
from collections import OrderedDict
import json
from pydoc import classname
from doublebottom import DoubleBottomStrategy


STRATEGY_CLASS = {}
STRATEGY_CLASS['DoubleBottom'] = DoubleBottomStrategy

class Engine(observer.Subject):
    
    settingFileName = 'CTA_setting.json'
    settingFileName = os.path.join(os.path.dirname(os.path.abspath(__file__)),settingFileName)
    
    def __init__(self):
        self.__event = observer.Event()
        self.__logEvent = observer.Event()
        self.__strategyEvent = observer.Event()
        self.__positionsEvent = observer.Event()
        self.strategyDict = {}
    def start(self):
        pass

    def stop(self):
        pass

    def join(self):
        pass

    def peekDateTime(self):
        pass
    def dispatch(self):
        pass
    
    def eof(self):
        pass
        
        
    def getLogEvent(self):
        
        return self.__logEvent
    
    def getStrategyEvent(self):
        
        return self.__strategyEvent
    def getPositionsEvent(self):
        return self.__positionsEvent
    #----------------------------------------------------------------------
    def getStrategyVar(self, name):
        """获取策略当前的变量字典"""
        if name in self.strategyDict:
            strategy = self.strategyDict[name]
            varDict = dict()
            
            for key,val in strategy.varList.items():
                varDict[val] = strategy.__getattribute__(key)
            
            return varDict
        else:
            self.writeCtaLog(u'策略实例不存在：' + name)    
            return None
    
    #----------------------------------------------------------------------
    def getStrategyParam(self, name):
        """获取策略的参数字典"""
        if name in self.strategyDict:
            strategy = self.strategyDict[name]
            paramDict = dict()
            
            for key,val in strategy.paramList.items():  
                paramDict[val] = strategy.__getattribute__(key)
            
            return paramDict
        else:
            self.writeCtaLog(u'策略实例不存在：' + name)    
            return None 
    #----------------------------------------------------------------------
    def getStrategyPositions(self,name):
        if name in self.strategyDict:
            strategy = self.strategyDict[name]
            if strategy.inited:
                return strategy.getPositions()
            else:
                return None
        else:
            self.writeCtaLog(u'策略实例不存在：' + name)    
            return None 
    #----------------------------------------------------------------------
    def loadStrategy(self, className):
        """载入策略"""
        
        # 获取策略类
        strategyClass = STRATEGY_CLASS.get(className, None)
        if not strategyClass:
            self.writeCtaLog(u'找不到策略类：%s' %className)
            return
        
        # 防止策略重名
        if className in self.strategyDict:
            self.writeCtaLog(u'策略实例重名：%s' %className)
        else:
            # 创建策略实例
            strategy = strategyClass(self)  
            self.strategyDict[className] = strategy
            
    #----------------------------------------------------------------------
    def initStrategy(self, name):
        """初始化策略"""
        if name in self.strategyDict:
            strategy = self.strategyDict[name]
            
            if not strategy.inited:
                strategy.initMe()
                self.getStrategyEvent().emit()
                self.writeCtaLog(u'策略实例%s初始化成功' %name) 
            else:
                self.writeCtaLog(u'请勿重复初始化策略实例：%s' %name)
        else:
            self.writeCtaLog(u'策略实例不存在：%s' %name)    
    #---------------------------------------------------------------------
    def startStrategy(self, name):
        """启动策略"""
        if name in self.strategyDict:
            strategy = self.strategyDict[name]
            
            if strategy.inited and not strategy.trading:
                strategy.startMe()
                self.writeCtaLog(u'策略实例%s启动成功' %name) 
                self.getStrategyEvent().emit()
        else:
            self.writeCtaLog(u'策略实例不存在：%s' %name) 
            
    def stopStrategy(self, name):
        """停止策略"""
        if name in self.strategyDict:
            strategy = self.strategyDict[name]
            
            if strategy.trading:
                strategy.stopMe()
                self.getStrategyEvent().emit()
        else:
            self.writeCtaLog(u'策略实例不存在：%s' %name)      
    #----------------------------------------------------------------------
    def getStrategyResult(self,name):
        """查看收益"""
        if name in self.strategyDict:
            strategy = self.strategyDict[name]
            
            if strategy.trading:
                strategy.checkResult()
        else:
            self.writeCtaLog(u'策略实例不存在：%s' %name)  
    #----------------------------------------------------------------------
    def loadSetting(self):
        """读取策略配置"""
        for className,_ in STRATEGY_CLASS.items():
            self.loadStrategy(className)
                
    
    def writeCtaLog(self,content):
        data = VtLogData()
        data.logContent=content
        self.__logEvent.emit({"data":data})
    def updatePositions(self,positions):
        self.__positionsEvent.emit(positions)
        
        
    

########################################################################
class VtBaseData(object):
    """回调函数推送数据的基础类，其他数据类继承于此"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        self.strategyName = ''                  # 策略名称        
        self.rawData = None                     # 原始数据
        
########################################################################
class VtLogData(VtBaseData):
    """日志数据类"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        super(VtLogData, self).__init__()
        
        self.logTime = time.strftime('%X', time.localtime())    # 日志生成时间
        self.logContent = u''                                   # 日志信息